<template>
  <el-dialog v-model="state.visible" :title="`${form.id ? '编辑' : '新增'}店铺配置`" center width="700">
    <el-form ref="formRef" :model="form" :rules="rules" @submit.native.prevent label-width="140px">
      <el-form-item prop="configType" label="配置分组">
        <el-select v-model="form.configType" @change="onConfigKeyChange" placeholder="请选择配置分组">
          <el-option
            v-for="(item, index) in configTypeList"
            :key="item.dictName"
            :value="item.dictName"
            :label="item.dictDescribe"
            >{{ item.dictDescribe }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item prop="configText" label="配置文本">
        <el-input v-model="form.configText" maxlength="20" placeholder="请输入配置文本"></el-input>
      </el-form-item>

      <el-form-item prop="formType" label="表单类型">
        <el-select v-model="form.formType" @change="onFormTypeChange" placeholder="请选择表单类型">
          <el-option
            v-for="(item, index) in formTypeList"
            :key="item.dictId"
            :value="item.dictName"
            :label="item.dictDescribe"
            >{{ item.dictDescribe }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item prop="formValue" label="表单选项" v-if="!['el-input', 'el-input-number'].includes(form.formType)">
        <div class="form-option" style="display: flex; align-items: center" v-for="(item, index) in form.formValue">
          <div class="input-line" style="margin-bottom: 4px">
            <el-input
              :key="'value' + index"
              v-model="item.value"
              placeholder="请输入值(Value)"
              maxlength="64"
              style="width: 130px; margin-right: 10px"
            ></el-input>
            <el-input
              :key="'label' + index"
              v-model="item.label"
              placeholder="请输入描述(Label)"
              maxlength="32"
              style="width: 220px; margin-right: 10px"
            ></el-input>
          </div>
          <el-button
            v-if="index !== 0 && form.formType != 'el-switch'"
            type="danger"
            link
            @click="handleDelOption(item)"
            >删除</el-button
          >
        </div>
        <div class="btns" style="width: 100%; margin-top: 10px" v-if="form.formType != 'el-switch'">
          <el-button type="primary" @click="handleAddOption">添加</el-button>
        </div>
      </el-form-item>

      <el-form-item prop="configValue" label="表单取值" :key="Date.now()">
        <el-input
          v-if="form.formType === 'el-input'"
          v-model="form.configValue"
          placeholder="请输入配置取值"
          type="textarea"
          maxlength="128"
        ></el-input>
        <el-input-number
          v-else-if="form.formType === 'el-input-number'"
          v-model="form.configValue"
          placeholder="请输入配置取值"
          maxlength="20"
        ></el-input-number>
        <el-select v-else v-model="form.configValue" :multiple="'el-checkbox' == form.formType">
          <el-option
            v-for="(item, index) in form.formValue"
            :key="item.value"
            :value="item.value"
            :label="item.label"
            >{{ item.label }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item prop="hasDefault" label="是否必填">
        <el-switch
          v-model="form.hasDefault"
          :active-value="1"
          :inactive-value="0"
          active-text="必填"
          inactive-text="非必填"
          style="--el-switch-on-color: #f56c6c"
        ></el-switch>
      </el-form-item>

      <el-form-item prop="hasEditor" label="商家是否可编辑">
        <el-switch
          v-model="form.hasEditor"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
        ></el-switch>
      </el-form-item>
      <el-form-item prop="hasSyncData" label="同步到所有商家" v-if="form.hasEditor == 0">
        <el-switch
          v-model="form.hasSyncData"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
        ></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleOk">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { postShopConfigModelSave, postShopConfigModelUpdate } from '@/api/shop'
import { ElMessage } from 'element-plus'

const props = defineProps({
  configTypeList: {
    type: Array,
    default: []
  },
  formTypeList: {
    type: Array,
    default: []
  }
})

const emits = defineEmits(['ok'])

const formRef = ref(null)
const form = reactive({
  id: '',
  configType: '', // 分组
  // configKey: "", // 标识（与configText 对应）
  configText: '', // 配置文本
  configValue: '', // 默认值
  formType: 'el-input', // 表单类型
  formValue: [], // 表单选项
  hasDefault: 0, // 是否必填
  hasEditor: 1, // 是否可编辑
  hasSyncData: 0 // 是否同步所有商家
})
const state = reactive({
  visible: false
})

function validateFormValueOptions(rule, value, callback) {
  console.log('value', value)
  if (value.length === 0) {
    callback(new Error('请添加表单选项'))
  } else if (value.length) {
    const hasEmpty = value.some(
      (item) => item.label === '' || item.label === null || item.value === '' || item.value === null
    )
    const hasDuplicate = value.some(
      (item, index) => value.findIndex((item2, index2) => item2.value === item.value) !== index
    )
    if (hasEmpty) {
      callback(new Error('表单项不能为空'))
    } else if (hasDuplicate) {
      callback(new Error('表单项(Value)不能有重复'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const rules = reactive({
  configType: [{ required: true, message: '请选择配置分组', trigger: 'blur' }],
  configText: [{ required: true, message: '请输入配置文本', trigger: 'blur' }],
  formValue: [{ required: true, validator: validateFormValueOptions, trigger: 'blur' }],
  formType: [{ required: true, message: '请选择表单类型', trigger: 'blur' }],
  configValue: [{ required: true, message: '请输入表单取值', trigger: 'blur' }],
  hasDefault: [{ required: true, message: '请选择是否必填', trigger: 'blur' }],
  hasEditor: [{ required: true, message: '请选择是否可编辑', trigger: 'blur' }],
  hasSyncData: [{ required: true, message: '请选择是否同步到所有商家', trigger: 'blur' }]
})

function handleAddOption() {
  form.formValue.push({
    idx: form.formValue.length,
    value: form.formValue.length,
    label: '自定义' + form.formValue.length
  })

  console.log('form.formValue', form.formValue)
}

function handleDelOption(item) {
  form.formValue = form.formValue.filter((option) => option.idx !== item.idx)

  form.formValue.forEach((e, i) => {
    e.idx = i
    // e.label = "选项" + e.value;
  })

  console.log('form.formValue', form.formValue)
}

function onConfigKeyChange(value) {
  console.log('key', value)
  // form.configType = value;
}

function onFormTypeChange(value) {
  if (value === 'el-select') {
    form.formValue = [
      { idx: 0, value: 0, label: '选项0' },
      { idx: 1, value: 1, label: '选项1' }
    ]
    setTimeout(() => {
      form.configValue = [0]
    }, 0)
  } else if (value === 'el-radio') {
    form.formValue = [
      { idx: 0, value: 0, label: '选项0' },
      { idx: 1, value: 1, label: '选项1' }
    ]
    setTimeout(() => {
      form.configValue = 0
    })
  } else if (value === 'el-checkbox') {
    form.formValue = [
      { idx: 0, value: 0, label: '选项0' },
      { idx: 1, value: 1, label: '选项1' }
    ]
    setTimeout(() => {
      form.configValue = [0]
    }, 0)
  } else if (value === 'el-switch') {
    form.formValue = [
      { idx: 0, value: 0, label: '选项0' },
      { idx: 1, value: 1, label: '选项1' }
    ]
    setTimeout(() => {
      form.configValue = 0
    })
  } else {
    form.formValue = []
  }

  form.formValue = form.formValue
}

function close() {
  state.visible = false
}

function show({ data, type }) {
  console.log(data, type)
  if (type === 'add') {
    state.visible = true
    form.id = ''
    form.configType = ''
    form.configValue = ''
    form.configText = ''
    form.formType = 'el-input'
    form.formValue = []
    form.hasDefault = 0
    form.hasEditor = 1
    form.hasSyncData = 0
    setTimeout(() => {
      formRef.value?.clearValidate()
    }, 0)
  } else if (type === 'edit') {
    state.visible = true

    form.id = data.id
    form.configType = data.configType
    form.configValue = /^\d+$/.test(data.configValue) ? +data.configValue : data.configValue + ''
    form.configText = data.configText
    form.formType = data.formType
    form.hasDefault = +data.hasDefault
    form.hasEditor = data.hasEditor
    form.hasSyncData = data.hasSyncData
    form.formValueOptions = data.formValueOptions
    if (!['el-input', 'el-input-number'].includes(data.formType)) {
      form.formValue = JSON.parse(data.formValue || '[]')
    } else {
      form.formValue = []
    }
    // 多选用el-select-multiple，这里el-select为单选
    // if (["el-select", "el-checkbox"].includes(form.formType)) {
    if ('el-checkbox' == form.formType) {
      setTimeout(() => {
        form.configValue = (data.configValue + '').split(',')
      }, 0)
    }
  }
}

function handleOk() {
  formRef.value.validate((valid) => {
    if (valid) {
      const api = form.id ? postShopConfigModelUpdate : postShopConfigModelSave
      const params = {
        ...form,
        configValue: form.configValue.toString(),
        hasDefault: +form.hasDefault,
        hasSyncData: form.hasEditor == 1 ? 0 : form.hasSyncData,
        formValue: JSON.stringify(form.formValue || [])
      }
      api(params)
        .then((res) => {
          if (res.code === '') {
            ElMessage.success('操作成功')
            close()
            emits('ok')
          }
        })
        .catch(() => {})
    }
  })
}

defineExpose({
  show
})
</script>
